#!/usr/bin/env python

import roslib,sys
roslib.load_manifest('picasa')
import rospy

from picasa.srv import *

import gdata.photos.service
import gdata.media
from gdata.photos.service import GooglePhotosException
from gdata.service import BadAuthentication, CaptchaRequired

from PIL import Image

class Picasa:
    url = '/data/feed/api/user/default/albumid/%s'

    def __init__( self, email, password, album = 'default'):
        client = gdata.photos.service.PhotosService()
        client.email    = email
        client.password = password
        client.source   = 'harris-the-robotic-photographer'
        self.client = False
        try:
            client.ProgrammaticLogin()
            self.client = client
        except CaptchaRequired:
            rospy.logerr('Google has started requiring captchas for Picasa.')
        except BadAuthentication:
            rospy.logerr('The credentials provided are incorrect.')
        except Exception as e:
            rospy.logerr('An unexpected error occurred.')
        self.defaultAlbum = album

    def _getType(self, filename):
        return Image.open(filename).format

    def postPhoto(self, req): 
        if not self.client:
            return False
        filename = req.file
        album = req.album or self.defaultAlbum
        title = req.title or 'Untitled Photo'
        description = req.description or ''
        url = self.url % (album)
        retVal = False
        try:
            type = self._getType(filename).lower()
            rospy.loginfo('Uploading file of type %s', type)
            self.client.InsertPhotoSimple(
                url,
                title,
                description,
                filename,
                content_type='image/' + type
            )
            retVal = True
        except GooglePhotosException as e:
            rospy.logerr('Failed to save photo %s, server responded:  %s', filename, e.reason)
        except IOError as e:
            rospy.logerr('I/O Error: ' + e.strerror)
        except Exception as e:
            rospy.logerr('An unexpected error occurred')
        return retVal

    def createAlbum(self, title, summary=''):
        return self.InsertAlbum(title, album)

def run(username, password):
    picasa = Picasa(username, password)
    def upload_image(filename):
        return picasa.postPhoto(filename)
    rospy.init_node('picasa_server')
    rospy.Service('upload_image', ImageUpload, upload_image)
    rospy.spin()

    

if __name__ == '__main__':
    username = rospy.get_param('/image_uploader/username','')
    password = rospy.get_param('/image_uploader/password','')
    if username != '' and password != '':
        run(username, password)
    else:
        print "Please provide a username and a password"
